# frozen_string_literal: true

require_relative '../../../spec_helper'
include Wpxf::Net::HttpOptions

describe Wpxf::Net::TyphoeusHelper do
  let(:subject) do
    Class.new(Wpxf::Module) do
      include Wpxf::Net::HttpClient
      include Wpxf::Net::TyphoeusHelper
    end.new
  end

  before :each do
    allow(subject).to receive(:full_uri).and_return('http://127.0.0.1/path')
  end

  describe '#advanced_typhoeus_options' do
    it 'contains Typhoeus options using values in the datastore' do
      subject.set_option_value('basic_auth_creds', 'root:toor')
      subject.set_option_value('proxy', '127.0.0.1')
      subject.set_option_value('proxy_auth_creds', 'root:toor')
      subject.set_option_value('verify_host', true)
      subject.set_option_value('http_client_timeout', 10_000)
      subject.set_option_value('verify_peer', false)

      expect(subject.advanced_typhoeus_options).to include(
        userpwd: 'root:toor',
        proxy: '127.0.0.1',
        proxyuserpwd: 'root:toor',
        ssl_verifyhost: 2,
        timeout: 10_000,
        ssl_verifypeer: false
      )
    end
  end

  describe '#standard_typhoeus_options' do
    it 'contains Tphoeus options using values in the datastore' do
      method = :get
      body = 'body'
      params = ['foo=bar']
      headers = { 'Foo' => 'Bar' }
      base_headers = subject.base_http_headers

      subject.set_option_value('follow_http_redirection', true)
      opts = subject.standard_typhoeus_options(method, params, body, headers)

      expect(opts).to include(
        method: method,
        body: body,
        params: params,
        headers: base_headers.merge(headers),
        followlocation: true
      )
    end
  end

  describe '#create_typhoeus_request_options' do
    it 'returns a merge of the standard and advanced request options' do
      method = :get
      body = 'body'
      params = ['foo=bar']
      headers = { 'Foo' => 'Bar' }

      expect(
        subject.create_typhoeus_request_options(method, params, body, headers)
      ).to eq(
        subject.standard_typhoeus_options(method, params, body, headers)
          .merge(subject.advanced_typhoeus_options)
      )
    end
  end

  describe '#create_typhoeus_request' do
    it 'returns a Typhoeus request' do
      expect(subject.create_typhoeus_request(method: :get, url: 'github.com'))
        .to be_a Typhoeus::Request
    end

    it 'creates a relative request if the url begins with a forward slash' do
      req = subject.create_typhoeus_request(method: :get, url: '/test.txt')
      expect(req.url).to eq 'http://127.0.0.1/path/test.txt'
    end

    it 'creates an absolute request if the url does not start with a forward slash' do
      req = subject.create_typhoeus_request(method: :get, url: 'http://www.github.com/')
      expect(req.url).to eq 'http://www.github.com/'
    end
  end
end
